/*
 * #depends subsonic-store.js
 */
Ext.ux.mattgoldspink.AjaxGridPanel = Ext.extend(Ext.Panel, {
    constructor: function(){
        Ext.apply(this, {
            items: [{
                xtype: 'list',
                fit: true,
                listeners: {
                    itemTap: this.handleItemTap
                },
                itemTpl: this.getSongViewTpl(),
                grouped: true,
                store: new Ext.ux.mattgoldspink.subsonic.stores.MusicStore({}),
                indexBar: true,
                itemSelector: '.row'
            }],
            cls: 'grid',
            fit: true,
            layout: 'fit'
        });
        Ext.ux.mattgoldspink.AjaxGridPanel.superclass.constructor.call(this);
		this.list = this.items.items[0];
		this.list.store.on('datachanged', this.resetScroll, this);
    },
	resetScroll: function(){
		this.list.scroller.scrollTo({
			x: 0,
			y: 0
		});
	},
    getSongViewTpl: function(){
        return new Ext.XTemplate(
            '<div id="{id}" class="row {[values.isDir? "dir" : "track"]}">',
                '<tpl if="isDir">',
                    '<div class="{typeOfRequest}"><strong>{name}</strong></div>',
                '</tpl>',
                '<tpl if="isDir === false || isDir === undefined">',
                    '<div class="cell title"><strong>{[Ext.util.Format.ellipsis(values.name, 22)]}</strong></div>',
                    '<div class="cell">{[Ext.util.Format.ellipsis(values.artist, 20)]}</div>',
                    '<div class="cell">{[Ext.util.Format.ellipsis(values.album, 20)]}</div>',
                    '<div class="cell duration">{[this.renderDuration(values.duration)]}</div>',
                '</tpl>',
            '</div>',{
            renderDuration: function(duration) {
                var secs = (duration % 60).toString();
                while (secs.length < 2) {
                    secs = 0 + '' + secs;
                }
                return Math.floor(duration / 60) + ':' + secs;
            }    
        });
    },
    handleItemTap: function(dataView, index, item, evt){
		if (Ext.get(item).hasCls('dir')) {
			Ext.dispatch({
				controller: 'Ext.ux.mattgoldspink.subsonic.controllers.SongView',
				action    : 'loadFolder',
				historyUrl: 'songView/' + Ext.get(item).first('div', true).className.trim() + '/' + item.id,
				id: item.id
			});
		} else {
			Ext.dispatch({
				controller: 'Ext.ux.mattgoldspink.subsonic.controllers.Player',
				action: 'playTracks',
				tracks: Ext.StoreMgr.get('Ext.ux.mattgoldspink.subsonic.stores.MusicStore').data,
				startAtTrack: index
			});
		}
    }
}); 